package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.project.Main;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author(王思翰)
 * @Description(类的描述)
 * @Date(创建时间) 2021/7/13 10:42
 */
@Configuration
@ComponentScan(basePackageClasses = Main.class)
@MapperScan("com.project.mapper") //扫描指定包中的mapper文件
@EnableTransactionManagement //允许使用@Transactional配置事务
public class MyBatisConfig {
    /**
     * 得到数据源
     *
     * @return 数据源对象
     */
    @Bean
    public DataSource getDateSource() {
        //阿里巴巴的数据源
        DruidDataSource dataSource = new DruidDataSource();
        //驱动
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //url
        dataSource.setUrl("jdbc:mysql://localhost:1234/testDB?characterEncoding=utf-8&allowMultiQueries=true");
        //用户名
        dataSource.setUsername("root");
        //密码
        dataSource.setPassword("lovo");

        //最大响应时间
        dataSource.setMaxWait(1000);
        //最小连接
        dataSource.setMinIdle(20);
        //设置最大连接数
        dataSource.setMaxActive(100);
        return dataSource;
    }

    /**
     * 配置会话工厂
     *
     * @return 会话工厂对象
     */
    @Bean
    public SqlSessionFactoryBean getFactory() {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //设置数据源
        factoryBean.setDataSource(this.getDateSource());
        //读取mybatis主配置文件
        factoryBean.setConfigLocation(
                new ClassPathResource("mybatis.cfg.xml")
        );
        return factoryBean;
    }

    /**
     * 配置事务管理器
     *
     * @return 事务管理器对象
     */
    @Bean
    public TransactionManager getTransaction() {
        DataSourceTransactionManager trans = new DataSourceTransactionManager();
        //配置数据源
        trans.setDataSource(this.getDateSource());

        return trans;
    }
}
